/****************************************************************************
**
** Copyright (C) 2009-2010 Mist Poryvaev.
** All rights reserved.
** Contact: Mist Poryvaev (mist.poryvaev@gmail.com)
**
** This file is part of the RailWorm project.
**
****************************************************************************/

#ifndef HttpTools_H
#define HttpTools_H

#include <QtNetwork>
#include <QtCore>

class OpenUrlThread: public QThread {
public:
	void start(QUrl Url);
protected:
	void run();
private:
	QUrl m_Url;
};

class HttpTools;
class ResponseHandler: public QObject {
	Q_OBJECT
        friend class HttpTools;

public:
	ResponseHandler(const QNetworkRequest	& Header, int _Encoding, int Id, const QByteArray & Data);
	~ResponseHandler();
	static QNetworkAccessManager g_NetworkManager;
	static QMap<int, ResponseHandler *> g_Responses;
	static QNetworkReply * Reply(int _Id);
private slots:
	void OnPageRequestFinished();
	void OnPageError(QNetworkReply::NetworkError code);
	void OnPageSslErrors(QList<QSslError> errors);
signals:
	void PageRequestFinished(QString Response, int Id, bool _Error);
private:
	QNetworkRequest m_Header;
	int m_Encoding;
	int m_Id;
	QUrl m_Url;
	QNetworkReply * m_Reply;
	QByteArray m_Data;

	void MakeRequest();
};

class HttpTools : public QObject {
public:
	enum Type {Text = 0, Form = 1};
	enum Encoding {Local8Bit = 0, Utf8 = 1};
	static int Request(QString _Host, QByteArray Data, Type _Type, Encoding _Encoding, QObject * Receiver = 0, const char * Slot = 0);
	static QString Extract(QNetworkReply * Reply, Encoding _Encoding);
	static QString PassHost();
	static QString TicketHost();
	static void AddQuery(const QString & Name, QByteArray Data);
	static void RemoveQuery(const QString & Name);
	static QByteArray Query(const QString & Name);
	static void SetProxy(QString Address, QString Port);
	static void OpenUrl(QUrl Url);
private:
	static QMap <QString, QByteArray> g_Queries;
	static QString g_ProxyAddress, g_ProxyPort;
	static int g_Id;
};

typedef HttpTools rzd;

#endif // HttpTools_H
